import constant from "@/config/constant";
import { FN } from "@Tea/model";
import { Emiter, EventType, TableName, isSuccessCode, useElMessageBox } from "@Tea/utils";
import { Ref, onMounted, onUnmounted, ref } from "vue";
import http from "@/api";
import { ElMessage } from "element-plus";
import { TableV2Type } from "@/components/TableV2";

type PageLimit = {
  currentPage: number,
  pageSize: number
}

/**
 * @vuese 传入 表明，获取操作table的函数
 * @param tableName 
 * @param onSearch 搜索函数
 * @returns 
 */
//  * @param alias 是否需要别名,默认false 如果传入true 返回的事件名会 `${tableName}_${evenType}`
export const useTableV2 = function (tableName: TableName, onSearch?: FN) {
  const tableLoading = ref(false)
  const emiter = Emiter.getInstance()
  //重置 pagination 的 currentPage 
  const resetCurPage = () => {
    emiter.emit(tableName, "resetCurPage")
  }

  // 卸载挂载在 Emitter 实例上的 table
  const removeTable = () => {
    emiter.removeTable(tableName)
  }

  // 设置 rowData
  const setRowData = (rawData:any[]) => {
    emiter.emit(tableName, "setRowData", rawData)
  }

  // 设置pagination 的total
  const setTotal = (total: number)=>{
    emiter.emit(tableName,"setTotal",total)
  }

  // 获取单选项的行
  const getRadioSelected = <T>() => emiter.emit(tableName, "getRadioSelected") as T
  // 处理选择的单选项
  const handleRadioRow = function <T>(callBack: (data: T) => any) {
    const data = getRadioSelected<T>()
    if (data) { 
      callBack(data)
    } else {
      ElMessage({
        type:"warning",
        message: "请选择一条数据"
      })
    }
  }
  // 获取复选框的行
  const getCheckboxRecords = <T>() => emiter.emit(tableName, "getCheckboxRecords") as T
  // 打开所有 tree 
  const setAllTreeExpand = () => emiter.emit(tableName, "setAllTreeExpand")
  // 关闭所有 tree
  const clearTreeExpand = () => emiter.emit(tableName, "clearTreeExpand")

  // 全选
  const setAllCheckboxRow = () => emiter.emit(tableName, 'setAllCheckboxRow')
  // 清除选择
  const clearCheckboxRow = () => emiter.emit(tableName, 'clearCheckboxRow')

  // 挂载查询函数,用于在分页时切换分页信息的查询
  const mountSearch = (serchFun: FN) => {
    emiter.on(tableName, "onSearch", serchFun || (()=> {
      console.error("您当前并没有挂载查询函数");
    }))
  }

  // 获取挂载在 当前table 的 pagination 的 page he size
  const getCurAndSize = ()=> emiter.emit<PageLimit>(tableName, `getCurAndSize`)
  
  // 返回带有 currentPage 和 size 的参数对象
  const assginPaging = <T extends {} = {}>(param: T) => {
    return Object.assign(getCurAndSize(), param) as T & PageLimit
  }

  /**
   * @use 普通的列表请求操作
   */
  const commonSearch = async <T extends any[]>(
    request: ReturnType<typeof http<T>>,
    loading: Ref<boolean> = tableLoading
  ) =>
  {
    try {
      loading.value = true
      
      const result = await request
      const { code, data, total } = result
      loading.value = false
      if (isSuccessCode(code)) {
        setRowData(data);
        (total !== undefined || total !== null) && setTotal(total)
      }
      return result
    } catch (e) {
      loading.value = false
      console.log(e);
    }
  }


  // 挂载
  onMounted(() => {
    mountSearch(onSearch)
  })

  // 页面卸载时卸载 Emiter 上的 对应的table
  onUnmounted(() => {
    // 开发环境点击保存文件会触发 组件的 onUnmounted,从而移除对应的事件 无法保存页面初始化存入的状态
    // 通过判断开发环境来阻止调用
    constant.env !== "dev" && removeTable()
  })

  //const aliasName = alias ? `${tableName}_` : ''
  
  return {
    clearCheckboxRow,
    setAllCheckboxRow,
    resetCurPage,
    removeTable,
    mountSearch,
    assginPaging,
    getCurAndSize,
    setTotal,
    setRowData,
    getRadioSelected,
    commonSearch,
    tableLoading,
    setAllTreeExpand,
    clearTreeExpand,
    handleRadioRow,
    getCheckboxRecords,
  }
};